import { useState } from 'react';
import {scheduleTask} from './scheduler'

type Option = {
  debounce?: boolean,
  delay?: number
}

export default function useSelfState<T>(value: T) {
  const [data, setData] = useState(value)

  function dispatch(value:T, option: Option = {}) {
    var delay = 0
    if (option.delay) {
      delay = option.delay
    }
    if (option.debounce) {
      delay = 250
    }

    var map = new Map<any, any>()
    map.set('delay', delay)
    map.set('cb', setData)
    map.set(setData, value)
    if (option.debounce) {
      map.set('debounce', true)
    }

    scheduleTask('normal', map)
  }
  return [data, dispatch] as [T, (value: T, o: Option) => any]
}